# -*- coding = utf-8 -*-
# @Time : 2021/6/29 8:43
# @Author : yzh
# @File : localQuery.py
# @Software : PyCharm
import json
import requests
import re
import execjs
import time

r_jwxt_login_url = 'https://authserver-443.webvpn.ecut.edu.cn/authserver/login?service=https%3A%2F%2F172-20-130-13.webvpn.ecut.edu.cn%2Fsso%2Fjziotlogin'
iPlanetDirectoryPro = ["", ""]
getltList = ["", "", "", "", ""]
webvpn_url = "https://webvpn.ecut.edu.cn/users/sign_in"
vpn_key_url = 'https://webvpn.ecut.edu.cn/vpn_key/update'


def querygrade(username,password):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3775.400 QQBrowser/10.6.4208.400"
    }
    req = requests.get(webvpn_url, headers=headers)
    csrfToken = re.findall(r'name="csrf-token" content="(.*?)"', req.text)[0]
    _astraeus_session = req.headers['set-cookie']

    r_vpn_login_data = {
        'utf8': '%E2%9C%93',  # ✓
        'authenticity_token': csrfToken,
        'user[login]': username,
        'user[password]': password,
        'user[dymatice_code]': 'unknown',
        "user[otp_with_capcha]": "false",
        'commit': '登录 Login'
    }
    r_vpn_login_headers = {
        "Host": "webvpn.ecut.edu.cn",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3775.400 QQBrowser/10.6.4208.400",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
        "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
        "Accept-Encoding": "gzip, deflate, br",
        "Cache-Control": "max - age = 0",
        "Connection": "keep-alive",
        "Referer": "https://webvpn.ecut.edu.cn/users/sign_in",
        "Cookie": _astraeus_session,
        "Upgrade-Insecure-Requests": "1"
    }
    r_vpn = requests.post(url = webvpn_url, data=r_vpn_login_data, headers=r_vpn_login_headers, allow_redirects=False)
    _astraeus_session = r_vpn.headers['set-cookie']
    r_vpn_key_headers = {
        'User-Agent': 'Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19',
        "Pragma": "no-cache",
        "Accept": "application/json, text/plain, */*",
        "Cookie": _astraeus_session,
        "Upgrade-Insecure-Requests": "1"
    }

    r_vpn_key = requests.get(vpn_key_url, headers=r_vpn_key_headers, allow_redirects=False)

    webvpn_username = 'webvpn_username=' + re.findall(r'webvpn_username=(.*?);', r_vpn_key.headers['set-cookie'])[0] + '; '
    _webvpn_key = '_webvpn_key=' + re.findall(r'_webvpn_key=(.*?);', r_vpn_key.headers['set-cookie'])[0] + '; '
    webvpn_cookie = r_vpn_key.headers['set-cookie']

    r_jwxt_login_headers = {
        'User-Agent': 'Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19',
        "Pragma": "no-cache",
        "Accept": "application/json, text/plain, */*",
        "Cookie": webvpn_cookie
    }
    r_jwxt = requests.get(r_jwxt_login_url, headers=r_jwxt_login_headers)

    getltList[0] = re.findall(r'name="lt" value="(.*?)"', r_jwxt.text)[0]
    getltList[1] = re.findall(r'name="execution" value="(.*?)"', r_jwxt.text)[0]
    getltList[2] = re.findall(r'pwdDefaultEncryptSalt = "(.*?)"', r_jwxt.text)[0]
    getltList[3] = 'route=' + re.findall(r'route=(.*?),', r_jwxt.headers['set-cookie'])[0] + ';'
    getltList[4] = 'JSESSIONID=' + re.findall(r'JSESSIONID=(.*?);', r_jwxt.headers['set-cookie'])[0] + ';'

    with open('apps/DjangoWeb/spider/tools/encrypt.wisedu.js', encoding='utf-8') as f:
        code = f.read()
        js_compile = execjs.compile(code)
        pwd1 = js_compile.call('encryptAES', password, getltList[2])

    r_jwxt_login_data = {
        'username': username,
        'password': pwd1,  # 需加密
        'lt': getltList[0],
        'dllt': 'userNamePasswordLogin',
        'execution': getltList[1],
        '_eventId': 'submit',
        'rmShown': 1
    }

    r_jwxt_login_headers = {
        'User-Agent': 'Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19',
        "Pragma": "no-cache",
        "Accept": "application/json, text/plain, */*",
        "Cookie": getltList[3] + webvpn_username + _webvpn_key + getltList[4]
    }
    r_jwxt_login = requests.post(r_jwxt_login_url, headers=r_jwxt_login_headers, data=r_jwxt_login_data,
                                 allow_redirects=False)
    # 第五次post登录教务系统
    iPlanetDirectoryPro[0] = 'iPlanetDirectoryPro=' + \
                             re.findall(r'iPlanetDirectoryPro=(.*?);', r_jwxt_login.headers['set-cookie'])[0] + '; '
    iPlanetDirectoryPro[1] = re.findall(r'<a href="(.*?)"', r_jwxt_login.text)[0]


    UserAgent = "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19"
    cookie1 = webvpn_username + _webvpn_key + iPlanetDirectoryPro[0]

    # 进入ticket拿jsessionid
    url = iPlanetDirectoryPro[1]
    Ticket1Headers = {
        "User-Agent": UserAgent,
        "Referer": "https://authserver-443.webvpn.ecut.edu.cn/",
        "Cookie": cookie1
    }
    res1 = requests.get(url, headers=Ticket1Headers, allow_redirects=False)
    jsessionid = res1.headers['set-cookie'][:-9]

    cookie2 = jsessionid + webvpn_username + _webvpn_key + iPlanetDirectoryPro[0]
    Ticket2Headers = {
        "User-Agent": UserAgent,
        "Referer": "https://authserver-443.webvpn.ecut.edu.cn/",
        "Cookie": cookie2
    }
    url2 = 'https://172-20-130-13.webvpn.ecut.edu.cn/sso/jziotlogin;' + jsessionid
    res2 = requests.get(url2, headers=Ticket2Headers, allow_redirects=False)
    url3 = res2.headers['location']

    res3 = requests.get(url3, headers=Ticket1Headers, allow_redirects=False)
    new_jsessionid = res3.headers['set-cookie'][:-94]

    new_cookie = new_jsessionid

    # 查询成绩
    semesterData = {
        'xnm': '2020',
        'xqm': '12',
        '_search': 'false',
        'nd': int(round(time.time() * 1000)),
        'queryModel.showCount': '15',
        'queryModel.currentPage': '1',
        'queryModel.sortName': '',
        'queryModel.sortOrder': 'asc',
        'time': 0
    }
    QueryGradeUrl = 'http://172.20.130.13/jwglxt/cjcx/cjcx_cxDgXscj.html?doType=query&gnmkdm=N305005&su=' + username

    QueryGradeHeaders = {"User-Agent": UserAgent,
                         "Referer": 'http://172.20.130.13/jwglxt/cjcx/cjcx_cxDgXscj.html?gnmkdm=N305005&layout=default',
                         "Cookie": new_cookie}
    response = requests.post(url=QueryGradeUrl, data=semesterData, headers=QueryGradeHeaders)
    api = json.loads(response.content)
    return api
